package com.xuebank.nfe.nfecar.model.manager

import android.content.Context
import android.text.TextUtils

import com.google.gson.Gson

import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.MyApplication
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.UsersModel

class UserInfoManager private constructor() : BaseModelManager() {
    internal var TAG = "UserModelManager"

    val isLogin: Boolean
        get() = null != mUser && null != mUser?.token

    var mUser: UsersModel? = null
        get() {
            if (null == field) {
                val mUserStr = SharedPreferencesUtil.getInstance(MyApplication.myApplicationContext).getString(Constants.LOGIN_USER)
                if (!TextUtils.isEmpty(mUserStr)) {
                    field = Gson().fromJson(mUserStr, UsersModel::class.java)
                }
            }
            return field
        }
        set(user) {
            if (user != null && user.token.isNullOrBlank() && null != mUser && !mUser?.token.isNullOrBlank()) {
                val token = mUser?.token
                field = user
                mUser?.token = token
            } else
                field = user

            if (null != user ) {
                SharedPreferencesUtil.getInstance(MyApplication.myApplicationContext).applyString(Constants.LOGIN_USER,
                        Gson().toJson(mUser))
            }
        }


    fun logOut(context: Context) {
        mUser = null
        SharedPreferencesUtil.getInstance(context).removeByKey(Constants.LOGIN_USER)
    }

    companion object {
        @Volatile private var mUserManager: UserInfoManager? = null

        fun release() {
            if (null != mUserManager) {
                mUserManager?.mUser = null
                mUserManager = null
            }
        }
        //登出app
//        fun gotoLogin() {
//            if (instance.isLogin) instance.logOut(MyApplication.myApplicationContext)
//            LoginActivity.setUp(MyApplication.myApplicationContext)
//        }

        val instance: UserInfoManager
            get() {
                if (null == mUserManager) {
                    synchronized(UserInfoManager::class.java) {
                        if (null == mUserManager)
                            mUserManager = UserInfoManager()
                    }
                }
                return mUserManager!!
            }
    }
}
